#include "widget.h"
#include "ui_widget.h"
#include <QNetworkInterface>
#include <QDebug>
#include <QFileDialog>
#include <QTime>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowTitle("QTCPFILE");
    resize(400,600);
    serverInit();

    ui->lineEdit->setText("172.16.93.137");
}

void Widget::serverInit()
{
    m_qtcpServer = new QTcpServer(this);
    m_qtcpServer->listen(QHostAddress::Any,8888);
    connect(m_qtcpServer,SIGNAL(newConnection()),this,SLOT(dealNewConnection()));

    QString ip;
    QList<QHostAddress> AddressList = QNetworkInterface::allAddresses();
    foreach(QHostAddress address, AddressList){
        if(address.protocol() == QAbstractSocket::IPv4Protocol &&
                address != QHostAddress::Null &&
                address != QHostAddress::LocalHost){
            if (address.toString().contains("127.0.")){
                continue;
            }
            ip = address.toString();
            break;
        }
    }
    ui->label_myIp->setText("myIp:"+ip);
}
/*新客户端连接，客户端是发送方，服务器是接收方，马上new一个线程去接收文件*/
void Widget::dealNewConnection()
{
    /*客户端连接，要接收文件了*/
    QTcpSocket *tcpSocket = m_qtcpServer->nextPendingConnection();
    qDebug()<<tcpSocket->peerAddress().toString();
    ServerThread* serverThread = new ServerThread(tcpSocket);
    connect(serverThread,SIGNAL(sigFileInfo(QString,QString,qint64,qint64)),this,SLOT(dealRecSigFileInfo(QString,QString,qint64,qint64)));
    connect(serverThread,SIGNAL(sigOver(QTcpSocket*,QString,bool)),this,SLOT(dealRecSigOver(QTcpSocket*,QString,bool)));
    serverThread->start();
    m_mapTcpServer.insert(tcpSocket,serverThread);
    qDebug()<<"dealNewConnection:";
}
/*是否是才开始传输*/
bool Widget::getReceiveFirst(QString name)
{
    if(m_ListRecFirst.length() == 0)
        return true;

    for (int i=0;i<m_ListRecFirst.length(); ++i) {
        if(name == m_ListRecFirst.at(i)){
            return false;
        }
    }
    return true;
}
/*传入文件名，返回传输界面,这里是接收端*/
Form* Widget::getReceiveForm(QString fileNameTime)
{
    QMap<QString,Form*>::iterator itor;
    for (itor = m_mapReceive.begin(); itor != m_mapReceive.end(); ++itor) {
        if(itor.key() == fileNameTime){
            return itor.value();
        }
    }
}
/*传入tcp，返回传输线程，这里是接收端*/
ServerThread *Widget::getServerThread(QTcpSocket* tcp)
{
     QMap<QTcpSocket*,ServerThread*>::iterator itor;
     for (itor = m_mapTcpServer.begin(); itor != m_mapTcpServer.end(); ++itor) {
         if(itor.key() == tcp){
             return itor.value();
         }
     }
}
/*传入文件名，返回传输界面，这里是发送端*/
Form *Widget::getSendForm(QString fileNameTime)
{
    QMap<QString,Form*>::iterator itor;
    for (itor = m_mapSend.begin(); itor != m_mapSend.end(); ++itor) {
        if(itor.key() == fileNameTime){
            return itor.value();
        }
    }
}
/*传入文件名，返回传输线程,这里是发送端*/
ClientThread *Widget::getClientThread(QString fileNameTime)
{
    QMap<QString,ClientThread*>::iterator itor;
    for (itor = m_mapClient.begin(); itor != m_mapClient.end(); ++itor) {
        if(itor.key() == fileNameTime){
            return itor.value();
        }
    }
}

Widget::~Widget()
{
    delete ui;
}
/*更新接收进度*/
void Widget::dealRecSigFileInfo(QString name, QString filePath, qint64 size, qint64 received_size)
{
    /*更新接收进度*/
    qApp->processEvents();

    if(getReceiveFirst(name)){
        Form* form = new Form(name.section("##",0,0),size);
        ui->verticalLayout_server->addWidget(form);
        m_ListRecFirst.append(name);
        m_mapReceive.insert(name,form);
    }
    getReceiveForm(name)->updateProcess(received_size);
}
/*完事了，回收处理线程，这里是接收端*/
void Widget::dealRecSigOver(QTcpSocket* tcp,QString name,bool bl)
{
    /*文件接收完毕，关闭线程*/
    ServerThread* serverThread = getServerThread(tcp);
    serverThread->deleteData();
    serverThread->exit();
    serverThread->wait();
    serverThread->deleteLater();

    getReceiveForm(name)->setStatus(bl);
    qDebug()<<"dealRecSigOver:";
}
/*更新发送进度*/
void Widget::dealSendSigFileInfo(QString name, qint64 received_size)
{
    /*更新发送进度*/
    qApp->processEvents();
    getSendForm(name)->updateProcess(received_size);
}
/*完事了，回收处理线程，这里是发送端*/
void Widget::dealSendSigOver(QString fileTime,bool bl)
{
    qDebug()<<"dealSendSigOver:";
    /*文件发送完毕，关闭线程*/
    ClientThread* clientThread = getClientThread(fileTime);
    clientThread->disConnectTcp();
    clientThread->exit();
    clientThread->wait();
    clientThread->deleteLater();
    getSendForm(fileTime)->setStatus(bl);
}
/*发送文件，选择完文件后，new一个线程去发送*/
void Widget::on_pushButton_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(this,"OPen","/usr/share/backgrounds");
    if(filePath.isEmpty())
        return;

    /*加上时间，区分ClientThread*/
    QDateTime current_date_time =QDateTime::currentDateTime();
    QString current_date =current_date_time.toString("MMddhhmmsszzz");

    qDebug()<<"current_date:"<<current_date;

    /*文件传输界面*/
    QFileInfo info(filePath);
    Form* form = new Form(info.fileName(),info.size());
    ui->verticalLayout_client->addWidget(form);
    qDebug()<<"filePath:"<<info.fileName()<<":"<<info.size();

    /*线程发送文件，这里传到线程的文件路径是已经加了当前时间字符串的，
     * 线程中会处理在获取正在的文件路径，
     * 加时间字符串是以免文件名相同，
     * 后面获取传输界面会有问题*/

    ClientThread* clientThread = new ClientThread(8888,ui->lineEdit->text(),filePath+"##"+current_date);
    connect(clientThread,SIGNAL(sigFileInfo(QString,qint64)),this,SLOT(dealSendSigFileInfo(QString,qint64)));
    connect(clientThread,SIGNAL(sigOver(QString,bool)),this,SLOT(dealSendSigOver(QString,bool)));
    clientThread->start();

    /*字典，<处理后的文件名，线程>，*/
    m_mapClient.insert(info.fileName()+"##"+current_date,clientThread);
    /*字典，<处理后的文件名，传输界面>，*/
    m_mapSend.insert(info.fileName()+"##"+current_date,form);
}

